<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { saveAs } from 'file-saver';
import * as htmlDocx from 'html-docx-js-typescript';
import { getCustomLabelListAction, getLabelTreeAction } from '@/service/api';
import { generateRandomCode, successMessage } from '@/utils/utils';

interface Props {
  logId?: number;
  fileName?: string;
  labelList?: any[];
}

const props = withDefaults(defineProps<Props>(), {
  logId: 0,
  fileName: '',
  labelList: () => []
});

const currentOneLevelButton = ref<number>(0);
const currentTwoLevelButton = ref<number>(0);

// 一级标签
const oneLevelLabelList = ref<any[]>([]);
// 二级标签
const twoLevelLabelList = ref<any[]>([]);
// 三级标签
const threeLevelLabelList = ref<any[]>([]);
// 三级标签的labelName
const threeLevelLabelName = ref<any[]>([]);
// 筛选出的内容
const resultList = ref<any[]>([]);

onMounted(() => {
  getLabelTreeDataAction();
});

watch(
  () => props.labelList,
  value => {
    if (value) {
      getCustomLabelAction();
    }
  },
  { deep: true }
);

const customLabelList = ref<any[]>([]);

// 查询自定义标签数据
async function getCustomLabelAction() {
  const params: any = {
    logId: props.logId
  };
  const { data, error } = await getCustomLabelListAction(params);
  if (!error) {
    customLabelList.value = data;
    if (data.length > 0) {
      if (oneLevelLabelList.value.length > 0) {
        const oneLevelItem: any = oneLevelLabelList.value[oneLevelLabelList.value.length - 1];
        if (oneLevelItem.labelName !== '自定义标签') {
          const customLabelObj: any = {
            id: '999a',
            labelName: '自定义标签',
            parentId: 0,
            type: 1,
            childList: [
              {
                id: generateRandomCode(3),
                labelName: '自定义标签',
                parentId: '999a',
                type: 1,
                childList: []
              }
            ]
          };
          oneLevelLabelList.value.push(customLabelObj);
        }
      }
    }
    oneLevelClick(0);
  }
}

const labelTreeData = ref<any[]>([]);

// 获取标签树数据
async function getLabelTreeDataAction() {
  const { data, error } = await getLabelTreeAction({});
  // console.log('data: ', data);
  if (!error) {
    labelTreeData.value = data;
    oneLevelLabelList.value = data;
    oneLevelClick(0);
    getThreeLevelLabelName();
  }
}

// 顶部一级标签点击事件
function oneLevelClick(index: number) {
  currentOneLevelButton.value = index;
  twoLevelLabelList.value = oneLevelLabelList.value[index].childList;
  currentTwoLevelButton.value = 0;

  if (twoLevelLabelList.value.length === 1 && twoLevelLabelList.value[0].labelName === '自定义标签') {
    twoLevelLabelList.value[0].childList = customLabelList.value;
    threeLevelLabelList.value = customLabelList.value;
  } else {
    threeLevelLabelList.value = twoLevelLabelList.value[0].childList;
  }
  getThreeLevelLabelName();
}

// 二级标签点击事件
function twoLevelClick(index: number) {
  currentTwoLevelButton.value = index;
  threeLevelLabelList.value = twoLevelLabelList.value[index].childList;
  getThreeLevelLabelName();
}

// 获取三级标签的labelName数据
function getThreeLevelLabelName() {
  threeLevelLabelName.value = [];
  threeLevelLabelName.value = threeLevelLabelList.value.map((item: any) => item.labelName);

  resultList.value = [];

  for (let i: number = 0; i < threeLevelLabelName.value.length; i++) {
    const labelName: string = threeLevelLabelName.value[i];

    const resultObj: any = {
      id: generateRandomCode(6),
      labelName,
      sentenceList: []
    };
    for (let j: number = 0; j < props.labelList.length; j++) {
      const labelObj: any = props.labelList[j];
      const labelArr: string[] = [];
      for (let k: number = 0; k < labelObj.labelBindings.length; k++) {
        const labelItem: string = labelObj.labelBindings[k];
        labelArr.push(labelItem.labelName);
      }
      if (labelArr.includes(labelName)) {
        resultObj.sentenceList.push(labelObj.sentence);
      }
    }

    if (resultObj.sentenceList.length > 0) {
      resultList.value.push(resultObj);
    }
  }
}

// 导出下载
async function downloadClick() {
  const downloadContent: string = downloadContentHandle();

  const formatContent: string = `
    	 	<!DOCTYPE html>
    	 	<html lang="en">
          <head>
              <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
              <title>${props.fileName}</title>
          </head>
          <body>
             ${downloadContent}
          </body>
        </html>`;

  const convertedFile = htmlDocx.asBlob(formatContent);

  // 生成链接并且下载
  convertedFile.then(fileData => {
    saveAs(fileData as Blob, `${props.fileName}.docx`, { encoding: 'UTF-8' });
    successMessage('文档下载成功');
  });

  // const saveParams: any = {
  //   contentList: sliceStringByLength(`<div>${downloadContent}</div>`, 40000)
  // };
  //
  // // console.log('内容：', `<div>${htmlContent}</div>`);
  //
  // const { VITE_OTHER_SERVICE_BASE_URL } = import.meta.env;
  // const otherUrl = JSON.parse(VITE_OTHER_SERVICE_BASE_URL);
  //
  // const { data, error } = await htmlToDocAction(saveParams);
  // if (!error) {
  //   saveAs(otherUrl.fileUrl + data, `${props.fileName}.docx`, { encoding: 'UTF-8' });
  //   successMessage('文档下载成功');
  // }
}

// 导出内容处理
function downloadContentHandle() {
  let downloadContent: string = '';
  const astyleStr: string = 'text-align: left; line-height: 150%; align-items: center;';
  for (let i: number = 0; i < oneLevelLabelList.value.length; i++) {
    const oneLevelItem: any = oneLevelLabelList.value[i];
    downloadContent += `<h1 style="${astyleStr}">${oneLevelItem.labelName}</h1>`;
    for (let j: number = 0; j < oneLevelItem.childList.length; j++) {
      const twoLevelItem: any = oneLevelItem.childList[j];

      const twoLevelObj: any = {
        id: generateRandomCode(6),
        labelName: twoLevelItem.labelName,
        sentenceList: []
      };

      for (let k: number = 0; k < twoLevelItem.childList.length; k++) {
        const threeLevelItem: any = twoLevelItem.childList[k];
        const threeLevelObj: any = {
          id: generateRandomCode(6),
          labelName: threeLevelItem.labelName,
          sentenceList: []
        };
        for (let j: number = 0; j < props.labelList.length; j++) {
          const labelObj: any = props.labelList[j];
          const labelArr: string[] = [];
          for (let k: number = 0; k < labelObj.labelBindings.length; k++) {
            const labelItem: string = labelObj.labelBindings[k];
            labelArr.push(labelItem.labelName);
          }
          if (labelArr.includes(threeLevelItem.labelName)) {
            threeLevelObj.sentenceList.push(labelObj.sentence);
          }
        }
        if (threeLevelObj.sentenceList.length > 0) {
          twoLevelObj.sentenceList.push(threeLevelObj);

          // downloadContent += `<h3 style="${astyleStr}">${threeLevelItem.labelName}</h3>`;
          // for (let l: number = 0; l < resultObj.sentenceList.length; l++) {
          //   downloadContent += `<p style="${astyleStr}">${threeLevelObj.sentenceList[l]}</p>`;
          // }
        }
      }

      if (twoLevelObj.sentenceList.length > 0) {
        downloadContent += `<h2 style="${astyleStr}">${twoLevelObj.labelName}</h2>`;
        for (let l: number = 0; l < twoLevelObj.sentenceList.length; l++) {
          const threeObjItem: any = twoLevelObj.sentenceList[l];
          downloadContent += `<h3 style="${astyleStr}">${threeObjItem.labelName}</h3>`;
          for (let j: number = 0; j < threeObjItem.sentenceList.length; j++) {
            downloadContent += `<p style="${astyleStr}">${threeObjItem.sentenceList[j]}</p>`;
          }
        }
      }
    }
  }
  return downloadContent;
}
</script>

<!-- 解析结果 -->
<template>
  <div>
    <div class="flex items-center justify-between">
      <div class="top-btn-box">
        <NButton
          v-for="(item, index) in oneLevelLabelList"
          :key="item.value"
          class="head-btn"
          :class="currentOneLevelButton === index ? 'head-btn-active' : ''"
          quaternary
          @click="oneLevelClick(index)"
        >{{ item.labelName }}</NButton>
      </div>
      <NButton class="top-btn" quaternary @click="downloadClick">
        <template #icon>
          <img src="@/assets/smart-eye/icon-module-download.png" width="20" alt="" />
        </template>
        导出下载
      </NButton>
    </div>
    <div class="content-box">
      <div class="left-box">
        <NScrollbar class="max-h-620px">
          <div
            v-for="(item, index) in twoLevelLabelList"
            :key="item.value"
            class="left-item"
            :class="currentTwoLevelButton === index ? 'left-item-active' : ''"
            @click="twoLevelClick(index)"
          >{{ item.labelName }}</div>
        </NScrollbar>
      </div>
      <div class="right-box">
        <NScrollbar v-if="resultList.length > 0" class="max-h-640px pl-15px pr-15px">
          <div v-for="item in resultList" :key="item.id" class="right-item">
            <span class="right-item-title">{{ item.labelName }}</span>
            <div
              v-for="(sentenceItem, sentenceIndex) in item.sentenceList"
              :key="sentenceIndex"
              class="right-item-content"
            >
              {{ sentenceItem }}
            </div>
          </div>
        </NScrollbar>
        <NEmpty v-else class="mt-260px" size="huge" description="暂无内容" />
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.top-btn-box {
  border-radius: 20px 20px 0 0;
  overflow: hidden;
  background-color: white;
  .head-btn {
    height: 50px;
    background: #836fff;
    padding: 0 23px;
    font-weight: 400;
    font-size: 18px;
    color: #ffffff;
    line-height: 50px;
    border-radius: 0;
    margin: 0 1px;
  }
  .head-btn-active {
    background: #ffffff;
    color: #836fff;
  }
  .head-btn:hover .head-btn-active:hover {
    background: #836fff;
    color: #ffffff;
  }
}
.top-btn {
  width: 127px;
  height: 40px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
  border: 1px solid #ffffff;
  font-weight: 400;
  font-size: 16px;
  color: #333333;
  line-height: 40px;
}
.content-box {
  display: flex;
  flex-direction: row;
  width: 100%;
  height: 655px;
  background-color: white;
  border-radius: 0 12px 12px 12px;
  .left-box {
    width: 315px;
    height: 100%;
    padding: 20px 0;
    border-right: 1px solid #e5e7eb;
    .left-item {
      width: 100%;
      padding: 0 20px;
      font-weight: 400;
      font-size: 18px;
      color: #333333;
      line-height: 42px;
      cursor: pointer;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .left-item-active {
      background: #e6e2ff;
      color: #816cfe;
    }
  }
  .right-box {
    width: calc(100% - 315px);
    height: 100%;
    display: flex;
    flex-direction: column;
    padding: 10px 0;
    .right-item {
      display: flex;
      flex-direction: column;
      .right-item-title {
        font-size: 18px;
        color: #333333;
        line-height: 34px;
        font-family: HarmonyOS_Sans_SC_Bold;
        font-weight: bold;
        padding: 0 5px;
      }
      .right-item-content {
        background-color: #f7f7f7;
        font-size: 16px;
        font-family: HarmonyOS_Sans_SC_Bold;
        margin: 3px 0;
        line-height: 34px;
        padding: 0 5px;
      }
    }
  }
}
</style>
